package cn.ac.iie.di.ban.jr.swb.rest.mq.utils;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Black-Laptop on 6/23/2017.
 */
public class WriteFile {

    public static Logger LOG = Logger.getLogger(WriteFile.class);

    private String fileDir;
    private String fileName;

    public WriteFile(String fileDir, String fileName) {
        this.fileDir = fileDir;
        this.fileName = fileName;
        createDir();
    }

    private void createDir() {
        File fDir = new File(fileDir + fileName);
        if (!fDir.getParentFile().exists()) {
            fDir.getParentFile().mkdirs();
        }
    }

    public void writeFileAppend(String datatype, String msg) {
        FileWriter fw = null;
        try {
            //如果文件存在，则追加内容；如果文件不存在，则创建文件
            File f=new File(fileDir + fileName);
            f.createNewFile();
            fw = new FileWriter(f, true);
        } catch (IOException e) {
            LOG.error(ExceptionUtils.getFullStackTrace(e));
        }
        PrintWriter pw = new PrintWriter(fw);
        pw.println(msg);
        pw.flush();
        try {
            fw.flush();
            pw.close();
            fw.close();
            LOG.info(datatype + " write 1 message to " + fileDir + fileName);
        } catch (IOException e) {
            LOG.error(ExceptionUtils.getFullStackTrace(e));
        }
    }

    public static String getFileDir(String baseDir, String dataType) {
        if (!baseDir.endsWith("/")) {
            baseDir += "/";
        }
        baseDir += dataType + "/";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String fileDir = baseDir + sdf.format(System.currentTimeMillis()) + "/";
        return fileDir;
    }

    public static String getFileName(String baseName){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
        String dateNowStr = sdf.format(date);
        String name = baseName + dateNowStr;
        return name;
    }
}
